<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Table, TableColumn } from '@/components/Table'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Icon } from '@/components/Icon'
import { BaseButton } from '@/components/Button'
import { Dialog } from '@/components/Dialog'
import { Form, FormSchema } from '@/components/Form'

import { ref, unref, computed } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import { pick } from 'lodash-es'
import { getTeachingVideoApi, saveTeachingVideoApi, deleteTeachingVideoApi } from '@/api/video'

// Table
const columns: TableColumn[] = [
  {
    field: 'id',
    label: '序号',
    type: 'index',
    width: 80
  },
  {
    field: 'title',
    label: '标题'
  },
  {
    field: 'videoUrl',
    label: '视频'
  },
  {
    field: 'action',
    label: '操作',
    width: 200,
    fixed: 'right',
    slots: {
      default: ({ row }) => {
        return (
          <div class="flex justify-center items-center">
            <BaseButton class="!ml-0" type="primary" size="small" onClick={() => onOpenDialog(row)}>
              {{
                icon: () => <Icon size={20} icon="carbon:edit" />,
                default: () => '编辑'
              }}
            </BaseButton>

            <BaseButton type="danger" size="small" onClick={() => onDelete(row)}>
              {{
                icon: () => <Icon size={20} icon="material-symbols:delete-outline" />,
                default: () => '删除'
              }}
            </BaseButton>
          </div>
        )
      }
    }
  }
]

const { tableMethods, tableState } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const { data, count } = await getTeachingVideoApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize)
    })
    return {
      list: data,
      total: count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

// Dialog
const visible = ref(false)
const isEdit = ref(false)
const title = computed(() => (isEdit.value ? '编辑' : '新增'))

//Form
const { formRegister, formMethods } = useForm()
const { getFormData, setValues, getElFormExpose } = formMethods

const formData = ref<any>({})

const uploadLoading = ref(false)

const { required } = useValidator()

const onBeforeClose = (done) => {
  if (uploadLoading.value) {
    // abortUploadFile()
  }
  done()
}

const schema = computed<FormSchema[]>(() => [
  {
    field: 'title',
    label: '标题名称',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  },
  {
    field: 'videoUrl',
    label: '视频',
    component: 'Input',
    formItemProps: {
      rules: [required()]
    }
  }
  // {
  //   field: 'videoUrl',
  //   label: '视频',
  //   formItemProps: {
  //     slots: {
  //       default: (formData) => {
  //         const httpRequest = async (options) => {
  //           uploadLoading.value = true
  //           const formDataTemp = new FormData()
  //           formDataTemp.append('file', options.file)
  //           const { data } = await uploadFile(formDataTemp)
  //           formData.videoUrl = data[0].fileUrl
  //           uploadLoading.value = false
  //         }

  //         const beforeUpload = (rawFile) => {
  //           // 校验文件
  //           if (rawFile.size > 100 * 1024 * 1024) {
  //             ElMessage.error('视频文件过大,请重新选择!')
  //             return false
  //           }
  //           return true
  //         }

  //         const onRemove = () => {
  //           formData.videoUrl = ''
  //         }

  //         return formData.videoUrl ? (
  //           <div class="w-full">
  //             <div class="flex border-[1px] border-dashed border-[#ccc] border-rd-[6px] p-[5px] mb-[5px]">
  //               <VideoPlayer url={formData.videoUrl} />
  //             </div>
  //             <BaseButton onClick={onRemove}>重新上传</BaseButton>
  //           </div>
  //         ) : (
  //           <ElUpload
  //             action="#"
  //             limit={1}
  //             accept="video/*"
  //             autoUpload={true}
  //             showFileList={false}
  //             disabled={uploadLoading.value}
  //             httpRequest={httpRequest}
  //             beforeUpload={beforeUpload}
  //           >
  //             {{
  //               default: () => (
  //                 <Icon
  //                   icon={uploadLoading.value ? 'line-md:uploading-loop' : 'mingcute:add-fill'}
  //                   size={40}
  //                 />
  //               ),
  //               tip: () => <div class="color-[#f59e0b]">文件大小不能超过100M</div>
  //             }}
  //           </ElUpload>
  //         )
  //       }
  //     },
  //     rules: [required('请上传视频')]
  //   }
  // }
])

// 新增
const onOpenDialog = async (row) => {
  visible.value = true
  if (row) {
    // 编辑
    isEdit.value = true
    setValues(pick(row, ['id', 'title', 'videoUrl']))
  } else {
    // 新增
    isEdit.value = false
  }
}

// 删除
const onDelete = async (row) => {
  ElMessageBox.confirm('是否删除该项内容?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await deleteTeachingVideoApi({ id: row.id })
      ElMessage.success('操作成功！')
      refresh()
    })
    .catch(() => {})
}
// 重置
const onReset = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.resetFields()
}
const disabled = ref(false)
// 立即提交
const onFormSubmit = async () => {
  const elFormExpose = await getElFormExpose()
  elFormExpose?.validate(async (isValid) => {
    if (!isValid) {
      ElMessage.warning('请填写完整信息')
      return
    } else {
      disabled.value = true
      const formData = await getFormData()
      saveTeachingVideoApi({ ...formData })
        .then(() => {
          visible.value = false
          ElMessage.success('操作成功！')
          refresh()
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          disabled.value = false
        })
    }
  })
}
</script>

<template>
  <ContentWrap title="教学设置">
    <div class="mb-4 flex justify-end">
      <BaseButton type="primary" @click="onOpenDialog">
        <template #icon>
          <Icon :size="20" icon="material-symbols:add" />
        </template>
        新增
      </BaseButton>
    </div>

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      :treeProps="{ children: 'list' }"
      :pagination="{ total: total }"
      :loading="loading"
      @refresh="refresh"
    />

    <!-- 新增提示-弹窗 -->
    <Dialog
      v-model="visible"
      :title="title"
      width="600"
      maxHeight="500px"
      :close-on-click-modal="false"
      :before-close="onBeforeClose"
    >
      <Form
        class="w-[500px] ml-[auto] mr-[auto]"
        labelPosition="top"
        v-loading="disabled"
        :schema="schema"
        :model="formData"
        :isCol="false"
        @register="formRegister"
      />
      <template #footer>
        <div class="text-center mb-[16px]">
          <BaseButton @click="onReset">重置</BaseButton>
          <BaseButton type="primary" :disabled="disabled" debounce @click="onFormSubmit"
            >立即提交</BaseButton
          >
        </div>
      </template>
    </Dialog>
  </ContentWrap>
</template>
